import os
import time
from models.pyttsx3_model import AudioFile
from config.pyttsx3_config import settings
from datetime import datetime
from entity.schema.pyttsx3_schema import TTSResponse

class AudioDAO:
    @staticmethod
    def create_audio_file(filename: str, text: str, voice: str, speed: int, volume: float) -> AudioFile:
        """创建音频文件记录"""
        file_path = os.path.join(settings.AUDIO_CACHE_DIR, filename)
        file_size = os.path.getsize(file_path) if os.path.exists(file_path) else 0

        return AudioFile(
            filename=filename,
            text=text,
            voice=voice,
            speed=speed,
            volume=volume,
            created_at=datetime.now(),
            file_size=file_size,
            file_path=file_path
        )

    @staticmethod
    def delete_audio_file(filename: str) -> bool:
        """删除音频文件"""
        file_path = os.path.join(settings.AUDIO_CACHE_DIR, filename)
        if os.path.exists(file_path):
            os.remove(file_path)
            return True
        return False

    @staticmethod
    def clean_old_files(max_age_hours: int = settings.MAX_FILE_AGE_HOURS) -> int:
        """清理过期文件，返回删除的文件数量"""
        current_time = time.time()
        deleted_count = 0

        for filename in os.listdir(settings.AUDIO_CACHE_DIR):
            file_path = os.path.join(settings.AUDIO_CACHE_DIR, filename)
            file_age = current_time - os.path.getmtime(file_path)
            if file_age > max_age_hours * 3600:
                os.remove(file_path)
                deleted_count += 1

        return deleted_count